package ru.reaperoq.taskmanager

import jakarta.servlet.http.HttpServletRequest
import ru.reaperoq.taskmanager.exceptions.TaskManagerException
import ru.reaperoq.taskmanager.models.User
import ru.reaperoq.taskmanager.repositories.UserRepository
import ru.reaperoq.taskmanager.services.JwtService
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

fun HttpServletRequest.getUserId(
    userRepository: UserRepository,
    jwtService: JwtService
): Long {
    val token = this.getHeader("Authorization").removePrefix("Bearer ")

    return jwtService.extractUsername(token)?.let { userRepository.findUserByUsername(it)?.id }
        ?: throw TaskManagerException.Unauthorized("Пользователь не найден")
}

fun HttpServletRequest.getUser(
    userRepository: UserRepository,
    jwtService: JwtService
): User {
    val token = this.getHeader("Authorization").removePrefix("Bearer ")
    return jwtService.extractUsername(token)?.let { userRepository.findUserByUsername(it) }
        ?: throw TaskManagerException.Unauthorized("Пользователь не найден")
}

fun LocalDateTime.toEpoch(): Long {
    return atZone(ZoneId.systemDefault()).toEpochSecond()
}

fun Long.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(this), ZoneId.systemDefault())
}